package sample;

import com.jfoenix.controls.JFXProgressBar;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import sample.common.DrawStandardLineChartImpl;
import sample.common.IDrawLineChart;
import sample.common.ViewStage;
import sample.model.City;
import sample.model.ExtremeData;
import sample.model.Result;
import sample.model.StandardData;
import sample.util.DownloadExcel;
import sample.util.HttpClientUtils;
import sample.util.Utils;

import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MainController implements Initializable {

    //    public TableView<StandardData> tableView_standard;
//    public TableView<ExtremeData> extremeDataTableView;
    public TreeView<Button> treeView;
    public ScrollPane scrollPane;
    public TabPane tabPane;
    public BorderPane borderPane;
    public TextField startDate;
    public TextField endDate;
    public Button OK;
    public MenuButton menuButton;
    private List<StandardData> standardDataList = new ArrayList<>();
    private List<ExtremeData> extremeDataList = new ArrayList<>();
    private Button b_bystation = null;
    private Button b_byyear = null;
    private Button extre_b_bystation = null;
    private Button extre_b_byyear = null;
    private Button bu_bystation = null;
    private Map<Tab, List<StandardData>> standardMap = new HashMap<>();
    private Map<Tab, List<ExtremeData>> extremeMap = new HashMap<>();
    private boolean downloadFlag;

    /**
     * 初始化，加载各种组件
     */
    @FXML
    public void initilalize(String role) {

        startDate.setTooltip(new Tooltip("起始月份"));
        endDate.setTooltip(new Tooltip("截止月份"));
        OK.setOnAction(e -> {
            if (!startDate.getText().equals("") && !endDate.getText().equals("")) {
//                System.out.println(standardDataList.isEmpty());
                Stream<StandardData> standardDataStream = standardDataList.stream()
                        .filter(standardData -> {
                            String text = startDate.getText();
                            return standardData.getMonth() >= Integer.valueOf(text);
                        })
                        .filter(standardData -> standardData.getMonth() <= Integer.valueOf(endDate.getText()));
                List<StandardData> collect = standardDataStream.collect(Collectors.toList());
                System.out.println(collect);
                dateConditionFilter(startDate.getText(), endDate.getText(), collect);
//                Utils.writeFilterDataToTableColumn(collect,);
            }
        });
//        TabPane tabPane =new TabPane();
//        tabPane.getSelectionModel().getSelectedItem().
//        Tab dateStartTap = new Tab();
////        dateTap.setText();
//        dateStartTap.setClosable(false);
//        TextField textField = new TextField();
//        dateStartTap.setContent(textField);
//        dateStartTap.setTooltip(new Tooltip("起始月份"));
//
//        Tab dateEndTap = new Tab();
//        dateEndTap.setTooltip(new Tooltip("结束月份"));
//        dateEndTap.setContent(new TextField());
//
//

//        tabPane.getTabs().addAll(dateStartTap,dateEndTap);


        //TODO
        init();

        TreeItem item = new TreeItem();
        /**************管理员***********/

        Button b_manager = new Button("管理员");
        b_manager.setGraphic(new ImageView(new Image("/image/管理员.png")));
        TreeItem<Button> man = new TreeItem<>(b_manager);
        Button b_standard = new Button("标准气象年数据");
        b_standard.setGraphic(new ImageView(new Image("/image/数据表.png")));
        b_bystation = new Button("按照站点查询");
        b_bystation.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        b_byyear = new Button("按年份查询");
        b_byyear.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        Button b_extreme = new Button("极端气象年数据");
        b_extreme.setGraphic(new ImageView(new Image("/image/数据表.png")));
        extre_b_bystation = new Button("按照站点查询");
        extre_b_bystation.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        extre_b_byyear = new Button("按年份查询");
        extre_b_byyear.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        Button b_download = new Button("导出数据");
        b_download.setGraphic(new ImageView(new Image("/image/下载数据.png")));
        Button b_add = new Button("导入标准气象年数据");
        Button extreme_b_add = new Button("导入极端气象年数据");
        b_add.setGraphic(new ImageView(new Image("/image/添加数据表.png")));
        extreme_b_add.setGraphic(new ImageView(new Image("/image/添加数据表.png")));
        TreeItem<Button> buttonTreeItem_standard = new TreeItem<>(b_standard);
        //manager
        TreeItem<Button> buttonTreeItem_extre = new TreeItem<>(b_extreme);

        Button deleteButton = new Button("删除数据");
        deleteButton.setGraphic(new ImageView(new Image("/image/删除.png")));
        Button deleteStandard = new Button("删除典型数据");
        deleteStandard.setOnAction(e -> deleteData(e));
        deleteStandard.setGraphic(new ImageView(new Image("/image/删除数据.png")));
        Button deleteExtreme = new Button("删除极端数据");
        deleteExtreme.setGraphic(new ImageView(new Image("/image/删除数据.png")));
        TreeItem<Button> deleteItem = new TreeItem<>(deleteButton);
        deleteItem.getChildren().addAll(
                new TreeItem<>(deleteStandard),
                new TreeItem<>(deleteExtreme)
        );

        buttonTreeItem_extre.getChildren().addAll(
                new TreeItem<>(extre_b_bystation),
//                new TreeItem<>(extre_b_byyear),
                new TreeItem<>(extreme_b_add)
        );

        buttonTreeItem_standard.getChildren().addAll(
                new TreeItem<>(b_bystation),
                new TreeItem<>(b_byyear),
                new TreeItem<>(b_add)
        );

        man.getChildren().addAll(
                buttonTreeItem_standard,
                buttonTreeItem_extre,
                new TreeItem<>(b_download),
                deleteItem
        );


        /************用户********/

        Button b_user = new Button("用户");

        Button bu_standard = new Button("标准气象年数据");
        bu_standard.setGraphic(new ImageView(new Image("/image/数据表.png")));
        TreeItem<Button> treeItem_standard = new TreeItem<>(bu_standard);
        bu_bystation = new Button("站点查询");
        bu_bystation.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        Button bu_byyear = new Button("年份查询");
        bu_byyear.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        treeItem_standard.getChildren().addAll(
                new TreeItem<>(bu_bystation),
                new TreeItem<>(bu_byyear)
        );
        Button bu_extreme = new Button("极端气象年数据");
        bu_extreme.setGraphic(new ImageView(new Image("/image/数据表.png")));
        TreeItem<Button> treeItem_extreme = new TreeItem<>(bu_extreme);
        Button extreme_bu_bystation = new Button("站点查询");
        bu_byyear.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        extreme_bu_bystation.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        Button extreme_bu_byyear = new Button("年份查询");
        extreme_bu_byyear.setGraphic(new ImageView(new Image("/image/数据查询.png")));
        Button bu_download = new Button("导出数据");
        bu_download.setGraphic(new ImageView(new Image("/image/下载数据.png")));
        treeItem_extreme.getChildren().addAll(
                new TreeItem<>(extreme_bu_bystation)
//                new TreeItem<>(extreme_bu_byyear)
        );
        b_user.setGraphic(new ImageView(new Image("/image/用户.png")));
        TreeItem<Button> user = new TreeItem<>(b_user);
        /***/


        user.getChildren().addAll(
                treeItem_standard,
                treeItem_extreme,
                new TreeItem<>(bu_download)
        );

        /**************功能***************/
        Button info = new Button("设置");
        info.setGraphic(new ImageView(new Image("/image/设置.png")));
        TreeItem<Button> infoTreeItem = new TreeItem<>(info);
        Button modifyPwd = new Button("修改密码");
        modifyPwd.setGraphic(new ImageView(new Image("/image/修改密码.png")));
        Button feedback = new Button("反馈");
        feedback.setGraphic(new ImageView(new Image("/image/反馈建议.png")));
        Button appInfo = new Button("应用信息");
        appInfo.setGraphic(new ImageView(new Image("/image/系统信息.png")));
        /**
         *该部分均为功能区
         */
        feedback.setOnAction(event -> {
            WebView webView = new WebView();
            WebEngine webEngine = webView.getEngine();
            webEngine.load("https://mail.qq.com");
            Stage stage = new Stage();
            AnchorPane anchorPane = new AnchorPane();
            anchorPane.getChildren().add(webView);
            Scene scene = new Scene(anchorPane);
            stage.setScene(scene);
            stage.setResizable(false);
            stage.setTitle("信息反馈");
            stage.show();
        });

        appInfo.setOnAction(event -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("@Copyright 西安建筑科技大学软件工程---韩坤\n" +
                    "版本号：\t\t\t\t1.0\n" +
                    "个人邮箱：\t\t\thk1450219359@outlook.com\n" +
                    "软件功能：\t\t\t全国气象站点数据：标准气象年数据、极端气象年数据\n\n"
            );
            alert.setTitle("系统信息");
            alert.show();
        });


        /***/


        infoTreeItem.getChildren().addAll(
                //TODO 没有做修改密码 new TreeItem<>(modifyPwd),
                new TreeItem<>(appInfo),
                new TreeItem<>(feedback)
        );

        if (role.equals("user"))
            item.getChildren().addAll(user, infoTreeItem);
        else
            item.getChildren().addAll(man, infoTreeItem);


        treeView.setRoot(item);
        treeView.setShowRoot(false);

        /**通过站点查询*/
//        b_bystation.setOnAction(event -> searchByStationId(event));
        b_bystation.setOnAction(event -> selectStation(event));
        /**通过站点查询极端气象年*/
        extre_b_bystation.setOnAction(event -> selectStation(event));
        /**通过时间查询*/
        b_byyear.setOnAction(event -> searchByYear(event));
//        extreme_bu_byyear.setOnAction(event -> searchByYear(event));

        /**导入excel数据*/
        b_add.setOnAction(event -> addExcelData(event));

        /**导入极端数据*/
        extreme_b_add.setOnAction(event -> addExcelData(event));

        /**下载数据*/
        b_download.setOnAction(event -> downloadData(event));
        /****************************/
        /**user的功能*/
        /**查询biaozhun气象年点击事件*/
        bu_bystation.setOnAction(event -> userSelectStation(event));
        bu_byyear.setOnAction(event -> searchByYear(event));
        bu_download.setOnAction(event -> downloadData(event));
        extreme_bu_bystation.setOnAction(event -> userSelectStation(event));

        tabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
//            if(newValue == null) {
//                newValue.setTooltip(new Tooltip("该数据已经失效，请重新查询"));
//            }
//            else {
                System.out.println(newValue.getText());
                if (standardMap.containsKey(newValue)) {
                    standardDataList = standardMap.get(newValue);
                    downloadFlag = false;
                } else {
                    extremeDataList = extremeMap.get(newValue);
                    downloadFlag = true;
                }
//            }
        });

        tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
        tabPane.selectionModelProperty().addListener((observable, oldValue, newValue) -> System.out.println("tabpane selection"));
    }

    private void deleteData(ActionEvent e) {
        Button source =(Button) e.getSource();
        String text = source.getText();
        Stage stage = new Stage();
        stage.initStyle(StageStyle.UNDECORATED);
        FlowPane flowPane = new FlowPane();
        flowPane.setAlignment(Pos.CENTER);
        flowPane.setHgap(10.0);
        flowPane.setVgap(10.0);
//        flowPane.requestFocus();
        stage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println(newValue);
            if (!newValue)
                stage.close();
        });
        String url = Url.QUERY_STATION_CITY;
        Result res = HttpClientUtils.sendGetHttp(url);
        List<Object> object = res.getObject();
        List<City> cities = Utils.parseCityList(object);
        for (int i = 0; i < cities.size(); i++) {
            City city = cities.get(i);
            Button button = new Button(city.getCity_name() + "(" + city.getStation_no() + ")");
            flowPane.getChildren().add(button);
        }
//        scrollPane.setContent(tableView_standard);
        stage.setScene(new Scene(flowPane));
        stage.show();
        Pattern pattern = Pattern.compile("[^0-9]");
        if(text.equals("删除典型数据")){
            flowPane.getChildren().forEach(node -> {
                Button button = (Button) node;
                button.setOnAction(event -> {
                    String str = button.getText();
                    Matcher matcher = pattern.matcher(str);
                    String s = matcher.replaceAll("").trim();
                    String deleteurl = Url.DELETE_STANDARD+s;
                    Result result = HttpClientUtils.sendDelete(deleteurl);
                    if(result.getCode().equals("200")){
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setContentText("删除成功");
                        alert.show();
//                        Dialog dialog = new Dialog();
//                        dialog.setContentText("删除成功");
//                        dialog.show();


                    }else{
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                    }
                });
            });
        }else{
            flowPane.getChildren().forEach(node -> {
                Button button = (Button) node;
                button.setOnAction(event -> {
                    String str = button.getText();
                    Matcher matcher = pattern.matcher(str);
                    String s = matcher.replaceAll("").trim();
                    String deleteurl = Url.DELETE_EXTREME+s;
                    Result result = HttpClientUtils.sendDelete(deleteurl);
                    if(result.getCode().equals("200")){
                        Alert alert = new Alert(Alert.AlertType.valueOf("删除成功"));
                        alert.show();
//                        Dialog dialog = new Dialog();
//                        dialog.setContentText("删除成功");
//                        dialog.show();
                    }else{
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                    }
                });
            });
        }
    }

    /**
     * 通过站点查询极端气象年
     *
     * @param
     */
//    private void searchExtremeByStation(ActionEvent event) {
//        TableView<ExtremeData> extremeDataTableView  = getExtremeTableView();
//        TextInputDialog dialog = new TextInputDialog();
//        dialog.setTitle("站点选择");
//        dialog.setContentText("请输入需要查询的站点号:");
//        Optional<String> result = dialog.showAndWait();
//        if (result.isPresent()) {
//            System.out.println("站点号（station_no）:" + result.get());
//        }
//        String station = result.get();
//
//        String url = Url.EXTREME_SEARCH_BY_STATION + station;
//        Result res = HttpClientUtils.sendGetHttp(url);
//        List<Object> object = res.getObject();
//        List<ExtremeData> extremeData = Utils.writeExtremeDataToTableColumn(object, extremeDataTableView);
//        Tab tab = new Tab(station+"(极端)");
////        tab.setClosable(true);
//        tabPane.getTabs().add(tab);
//        ScrollPane pane = new ScrollPane();
//        pane.setContent(extremeDataTableView);
//        tab.setContent(pane);
//        extremeMap.put(tab,extremeData);
////        scrollPane.setContent(null);
////        scrollPane.setContent(extremeDataTableView);
////        extremeDataList = extremeData;
////        standardDataList = null;
//    }
    public TableView getStandardTableView() {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("/fxml/standardTableView.fxml"));
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StandardTableViewController controller = fxmlLoader.getController();
        controller.init();
        return controller.tableView_standard;
    }

    public TableView getExtremeTableView() {
        FXMLLoader fxm = new FXMLLoader();
        fxm.setLocation(getClass().getResource("/fxml/tableView.fxml"));
        try {
            fxm.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        TableViewController tableViewController = fxm.getController();
//            extremeDataTableView = tableViewController.tableView_extreme;
        tableViewController.init();
        return tableViewController.tableView_extreme;
    }

    /**
     * 初始化   1.标准  tableview 2.极端 tableview
     */
    public void init() {

        menuButton.setTooltip(new Tooltip("折线图"));
        MenuItem menuItem1 = new MenuItem("干球温度折线图");
        MenuItem menuItem2 = new MenuItem("相对湿度折线图");
        MenuItem menuItem3 = new MenuItem("露点温度折线图");
        MenuItem menuItem4 = new MenuItem("风向折线图");
        MenuItem menuItem5 = new MenuItem("风速折线图");
        MenuItem menuItem6 = new MenuItem("云量折线图");
        MenuItem menuItem7 = new MenuItem("太阳总辐射折线图");
        MenuItem menuItem8 = new MenuItem("法向直射辐射折线图");
        MenuItem menuItem9 = new MenuItem("水平面散射辐射折线图");
        MenuItem menuItem10 = new MenuItem("大气压折线图");
        menuButton.getItems().addAll(menuItem1, menuItem2, menuItem3, menuItem4, menuItem5, menuItem6, menuItem7, menuItem8, menuItem9, menuItem10);
        menuItem1.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawDBTLineChart();
        });
        menuItem2.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawRHLineChart();
        });
        menuItem3.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawDPTLineChart();
        });
        menuItem4.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawWDLineChart();
        });
        menuItem5.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawWSLineChart();
        });
        menuItem6.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawCCLineChart();
        });
        menuItem7.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawTHLineChart();
        });
        menuItem8.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawNRLineChart();
        });
        menuItem9.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawDFLineChart();
        });
        menuItem10.setOnAction(event -> {
            IDrawLineChart drawLineChart = new DrawStandardLineChartImpl(standardDataList);
            drawLineChart.drawAPLineChart();
        });


//        try {
////            FXMLLoader fxmlLoader = new FXMLLoader();
////            fxmlLoader.setLocation(getClass().getResource("/fxml/standardTableView.fxml"));
////            fxmlLoader.load();
////            controller = fxmlLoader.getController();
//////            tableView_standard = controller.tableView_standard;
////            controller.init();
////            getStandardTableView();
////            scrollPane.setContent(null);
////            scrollPane.setContent(tableView_standard);
//
////            FXMLLoader fxm = new FXMLLoader();
////            fxm.setLocation(getClass().getResource("/fxml/tableView.fxml"));
////            fxm.load();
////            tableViewController = fxm.getController();
//////            extremeDataTableView = tableViewController.tableView_extreme;
////            tableViewController.init();
////                scrollPane.setContent(tableViewController.tableView_extreme);
////            getExtremeTableView();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public void initialize(URL location, ResourceBundle resources) {
    }

    public void selectStation(ActionEvent event) {
        Stage stage = new Stage();
        stage.initStyle(StageStyle.UNDECORATED);
        FlowPane flowPane = new FlowPane();
        flowPane.setAlignment(Pos.CENTER);
        flowPane.setHgap(10.0);
        flowPane.setVgap(10.0);
//        flowPane.requestFocus();
        stage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println(newValue);
            if (!newValue)
                stage.close();
        });
        String url = Url.QUERY_STATION_CITY;
        Result res = HttpClientUtils.sendGetHttp(url);
        List<Object> object = res.getObject();
        List<City> cities = Utils.parseCityList(object);
        for (int i = 0; i < cities.size(); i++) {
            City city = cities.get(i);
            Button button = new Button(city.getCity_name() + "(" + city.getStation_no() + ")");
            flowPane.getChildren().add(button);
        }
//        scrollPane.setContent(tableView_standard);
        stage.setScene(new Scene(flowPane));
        stage.show();
        Button source = (Button) event.getSource();
        if (source == b_bystation)
            addStandardAction(flowPane);
        else
            addExtremeAction(flowPane);
    }

    public void userSelectStation(ActionEvent event) {
        Stage stage = new Stage();
        stage.initStyle(StageStyle.UNDECORATED);
        FlowPane flowPane = new FlowPane();
        flowPane.setAlignment(Pos.CENTER);
        flowPane.setHgap(10.0);
        flowPane.setVgap(10.0);
//        flowPane.requestFocus();
        stage.focusedProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println(newValue);
            if (!newValue)
                stage.close();
        });
        String url = Url.QUERY_STATION_CITY;
        Result res = HttpClientUtils.sendGetHttp(url);
        List<Object> object = res.getObject();
        List<City> cities = Utils.parseCityList(object);
        for (int i = 0; i < cities.size(); i++) {
            City city = cities.get(i);
            Button button = new Button(city.getCity_name() + "(" + city.getStation_no() + ")");
            flowPane.getChildren().add(button);
        }
//        scrollPane.setContent(tableView_standard);
        stage.setScene(new Scene(flowPane));
        stage.show();
        Button source = (Button) event.getSource();
        if (source == bu_bystation)
            addStandardAction(flowPane);
        else
            addExtremeAction(flowPane);
    }


    public void addStandardAction(FlowPane flowPane) {
        Pattern pattern = Pattern.compile("[^0-9]");
        flowPane.getChildren().forEach(node -> {
            Button button = (Button) node;
            button.setOnAction(event -> {
                String text = button.getText();
                Matcher matcher = pattern.matcher(text);
                String s = matcher.replaceAll("").trim();
                searchStandardByStation(s);
            });
        });

    }

    public void addExtremeAction(FlowPane flowPane) {
        Pattern pattern = Pattern.compile("[^0-9]");
        flowPane.getChildren().forEach(node -> {
            Button button = (Button) node;
            button.setOnAction(event -> {
                String text = button.getText();
                Matcher matcher = pattern.matcher(text);
                String s = matcher.replaceAll("").trim();
                searchExtremeByStationId(s);
            });
        });
    }


    /**
     * @param station
     */
    public void searchStandardByStation(String station) {
        TableView<StandardData> tableView_standard = getStandardTableView();
        String url = Url.STANDARD_BY_STATION + station;
        Result res = HttpClientUtils.sendGetHttp(url);
        List<Object> object = res.getObject();
        List<StandardData> list = Utils.writeDataToTableColumn(object, tableView_standard);
        Tab tab = new Tab(station + "(标准)");
        tabPane.getTabs().add(tab);
        ScrollPane pane = new ScrollPane();
        pane.setContent(tableView_standard);
        tab.setContent(pane);
        standardDataList = list;
        standardMap.put(tab, list);
    }

    private void dateConditionFilter(String begin, String end, List<StandardData> list) {
        TableView<StandardData> tableView_standard = getStandardTableView();
        Utils.writeFilterDataToTableColumn(list, tableView_standard);
        Tab tab = new Tab("(" + begin + "," + end + ")");
        tabPane.getTabs().add(tab);
        ScrollPane pane = new ScrollPane();
        pane.setContent(tableView_standard);
        tab.setContent(pane);
//        standardDataList = list;
        standardMap.put(tab, list);
    }


    /**
     * @param station
     */
    public void searchExtremeByStationId(String station) {
        TableView<ExtremeData> extremeDataTableView = getExtremeTableView();

        String url = Url.EXTREME_SEARCH_BY_STATION + station;
        Result res = HttpClientUtils.sendGetHttp(url);
        List<Object> object = res.getObject();
        List<ExtremeData> extremeData = Utils.writeExtremeDataToTableColumn(object, extremeDataTableView);
        Tab tab = new Tab(station + "(极端)");
        tabPane.getTabs().add(tab);
        ScrollPane pane = new ScrollPane();
        pane.setContent(extremeDataTableView);
        tab.setContent(pane);
        extremeDataList = extremeData;
        extremeMap.put(tab, extremeData);

    }

    /**
     * 通过站点查询标准气象年数据
     * @param actionEvent
     */
//    public void searchByStationId(ActionEvent actionEvent) {
//
//        TableView<StandardData> tableView_standard = getStandardTableView();
//        TextInputDialog dialog = new TextInputDialog();
//        dialog.setTitle("站点选择");
////        dialog.setHeaderText("Look, a Text Input Dialog");
//        dialog.setContentText("请输入需要查询的站点号:");
//
//// Traditional way to get the response value.
//        Optional<String> result = dialog.showAndWait();
//        if (result.isPresent()) {
//            System.out.println("站点号（station_no）:" + result.get());
//        }
//        String station = result.get();
////        Button button = (Button) actionEvent.getSource();
////        if(button.getText().equals(""))
//        String url = Url.STANDARD_BY_STATION + station;
//        Result res = HttpClientUtils.sendGetHttp(url);
//        List<Object> object = res.getObject();
////        standardDataList.clear();
//        List<StandardData> standardDataList = Utils.writeDataToTableColumn(object, tableView_standard);
////        scrollPane.setContent(tableView_standard);
//        Tab tab = new Tab(station+"(标准)");
////        tab.setClosable(true);
//        tabPane.getTabs().add(tab);
//        ScrollPane pane = new ScrollPane();
//        pane.setContent(tableView_standard);
//        tab.setContent(pane);
//        standardMap.put(tab,standardDataList);
////        this.standardDataList = standardDataList;
////        extremeDataList = null;
//    }


    /**
     * 弹出年份和站点查询的输入框
     *
     * @param event
     */
    private void searchByYear(ActionEvent event) {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader();
            fxmlLoader.setLocation(getClass().getResource("/fxml/yearChoice.fxml"));
            fxmlLoader.load();
            YearChoiceController yearChoiceController = fxmlLoader.getController();
            yearChoiceController.choice(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过时间和年份查询标准气象年数据
     *
     * @param station
     * @param year
     */
    public void searchByStationAndYear(String station, String year) {
        TableView<StandardData> tableView_standard = getStandardTableView();
        String url = Url.STANDARD_BY_STATION_AND_YEAR + station + "/" + year;
        Result result = HttpClientUtils.sendGetHttp(url);
        List<Object> list = result.getObject();
        List<StandardData> dataList = Utils.writeDataToTableColumn(list, tableView_standard);
        Tab tab = new Tab(station + "(标准)");
        tab.setClosable(false);
        tabPane.getTabs().add(tab);
        ScrollPane pane = new ScrollPane();
        pane.setContent(tableView_standard);
        tab.setContent(pane);
        standardDataList = dataList;
        standardMap.put(tab, dataList);
//        scrollPane.setContent(tableView_standard);
//        this.standardDataList = standardDataList;
//        extremeDataList = null;
    }


    /**
     * 导入excel表数据 -> 添加到数据库中
     *
     * @param event
     */
    private void addExcelData(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        Stage stage = new Stage();
        stage.setTitle("excel数据表选择");
        File file = fileChooser.showOpenDialog(stage);
        if (file.isFile()) {
            String name = file.getName();
            if (name.endsWith(".xlsx") || name.endsWith("xls")) {
                String absolutePath = file.getAbsolutePath();
                Button button = (Button) event.getSource();
                String str = "";
                String url = "";
                if (button.getText().equals("导入标准气象年数据")) {
                    str = Utils.standardDataToJsonString(absolutePath);
                    url = Url.STANDARD_ADD_DATA;
                } else {
                    str = Utils.extremeDataToJsonString(absolutePath);
                    url = Url.EXTREME_ADD_DATA;
                }
//                ProgressIndicator progressIndicator = new ProgressIndicator();
                JFXProgressBar jfxProgressBar = new JFXProgressBar();
                ViewStage viewStage = new ViewStage(jfxProgressBar);
                MYTask myTask = new MYTask(viewStage);

                Result result = HttpClientUtils.sendPostHttp(url, str);
                System.out.println(Thread.currentThread().getName());
                Thread thread = new Thread(myTask);
                thread.setDaemon(true);
                thread.start();
                myTask.progressProperty().addListener((observable, oldValue, newValue) -> {
                    jfxProgressBar.setProgress(newValue.doubleValue());
                });
                while (result == null) {
                    System.out.println(result.getCode());
                }
                System.out.println(result.getMsg());
            }
        }

    }

    /**
     * 下载刚才查询的数据到excel表中   ----下载到本地
     *
     * @param event
     */
    private void downloadData(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("下载数据");
        Stage stage = new Stage();
        File file = fileChooser.showSaveDialog(stage);
        String name = file.getName();
        XSSFWorkbook excel = null;
        if (!downloadFlag)
            excel = DownloadExcel.downloadStandardExcel(name, standardDataList);
        else
            excel = DownloadExcel.downloadExtremeExcel(name, extremeDataList);
        try {
            OutputStream outputStream = new FileOutputStream(file);
            excel.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

/**
 * 导入数据的时候的一个任务：
 * 功能：倒计时5s，以表示：完成excel数据并成功导入到数据库中
 */
class MYTask extends Task<Integer> {

    private ViewStage viewStage;

    public MYTask(ViewStage viewStage) {
        this.viewStage = viewStage;
        viewStage.stageShow();

    }

    @Override
    protected Integer call() throws Exception {
        int iterations;
        for (iterations = 0; iterations <= 10; iterations++) {
            if (isCancelled()) {
                updateMessage("Cancelled");
                break;
            }
            updateProgress(iterations, 10);
            Thread.sleep(500);
        }
        viewStage.closeAlert();
        return 1;
    }

    @Override
    protected void updateProgress(double workDone, double max) {
        super.updateProgress(workDone, max);
        System.out.println(workDone / max);
        System.out.println("updataprogress");

    }
}

